package gui;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Gauge;
import midlet.MidletCielsa;
import util.CommandBuilder;

/**
 *
 * @author Dikas
 */
public class FrmImprimir extends Form implements CommandListener {

    private ChoiceGroup cgImpresora;    
    private Gauge gCargando;
    
    private Command cmdOk;
    private Command cmdAtras;
    
    private Displayable previousDisplayable;
    private MidletCielsa midlet;
    private Thread hilo;
    private Thread hilo1;

    public FrmImprimir(MidletCielsa midlet, Displayable previousDisplayable) {
        super("Imprimir Comprobante");
        this.previousDisplayable = previousDisplayable;
        this.midlet = midlet;
        this.cgImpresora = new ChoiceGroup("Impresoras", ChoiceGroup.POPUP);
        cgImpresora.append("Cannon", null);
        cgImpresora.append("HP", null);        
        this.cmdAtras = CommandBuilder.getBack();
        this.cmdOk = CommandBuilder.getOk();
        append(cgImpresora);
        addCommand(cmdAtras);
        addCommand(cmdOk);    
        setCommandListener(this);
    }

    public void commandAction(Command c, Displayable d) {
        if ( c == cmdAtras)
            midlet.setDisplay(previousDisplayable);
        else if ( c == cmdOk)
        {
            gCargando = new Gauge("Imprimiendo", false, Gauge.INDEFINITE, 0);
            append(gCargando);
            hilo = new Thread(new HiloSincronizaDatos());
            hilo.start();
            hilo1 = new Thread(new HiloAnimacionGauge());
            hilo1.start();
        }
    }

    private class HiloSincronizaDatos implements Runnable {

        public void run() {            
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }     
            midlet.setDisplay(previousDisplayable);
        }
    }

    private class HiloAnimacionGauge implements Runnable {

        public void run() {
            while (true) {
                gCargando.setValue(Gauge.INCREMENTAL_UPDATING);
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            }
        }
    }
}
